package com.huakai.springenv;

import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

public class LogParser {

    public static void main(String[] args) throws JSONException {
        List<JSONObject> logs = parseLog("C:\\Users\\huakai\\Desktop\\inner.log");

        HashMap<String, Integer> ipCountsMap = new HashMap<>();
        for (JSONObject log : logs) {
            String ip = log.getJSONObject("json").getString("ip");
            ipCountsMap.put(ip, ipCountsMap.getOrDefault(ip, 0) + 1);
        }
        ipCountsMap.entrySet().stream().filter(x -> x.getValue() > 20)
                .collect(Collectors.toMap(x -> x.getKey(), y -> y.getValue()))
                .forEach((ip, integer) -> System.out.println(ip + " " + integer));
    }


    private static List<JSONObject> parseLog(String filePath) {
        List<JSONObject> result = new ArrayList<>();
        StringBuilder currentJson = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                currentJson.append(line).append("\n"); // Append line and newline character
                if (line.trim().endsWith("}")) { // Check if this is the end of a JSON object
                    JSONObject jsonObject = new JSONObject(currentJson.toString());
                    result.add(jsonObject);
                    currentJson.setLength(0); // Reset StringBuilder for next JSON object
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
        return result;
    }
}